package com.seqb.common.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import com.seqb.utils.JsonUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 微博定时任务
 * @description 请填写相关描述
 * @date 2020/10/19
 */
public class WeiBoJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(DongdongMengChongJob.class);
    public static HttpHeaders headers = new HttpHeaders();

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        headers = new HttpHeaders();
        try {
            Object taskParams = redisUtils.get("taskParams");
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("WeiBoJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                        }
                    }
                }
            }
            LOGGER.info("微博定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            checkIn();
            LOGGER.info("微博定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查登录任务操作
     */
    public boolean checkIn() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://m.weibo.cn/c/checkin?from=10AA195010";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String st = "";
                //将从cookie中获取set
                List<String> cookies = responseEntity.getHeaders().get("Set-Cookie");
                for (String cookieStr : cookies) {
                    String[] cookieArr = cookieStr.split(";");
                    String cookieItem = cookieArr[0];
                    Cookie cookie = new Cookie(cookieItem.split("=")[0], cookieItem.split("=")[1]);
                    if (cookie.getName().equals("XSRF-TOKEN")) {
                        st = cookie.getValue();
                    }
                }
                //每天签到任务
                perSignIn(st);
            }
        } catch (Exception e) {
            System.out.println("微博定时器-检查登录任务执行失败：" + e.getMessage());
        }
        return false;

    }

    /**
     * 每天签到任务操作
     */
    public boolean perSignIn(String st) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://m.weibo.cn/c/checkin/ug/v2/signin/signin?st=" + st;
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                entityBody = StringEscapeUtils.unescapeJava(entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                LOGGER.info("微博每天签到任务操作：" + result.getString("msg"));
                return true;
            }
        } catch (Exception e) {
            System.out.println("微博定时器-每天签到任务执行失败：" + e.getMessage());
        }
        return false;
    }
}
